package com.wsm.common.utils;

import com.wsm.common.config.BaseConfig;
import com.wsm.common.config.CloseConfig;
import com.wsm.common.enums.CloseKey;
import com.wsm.common.enums.ConfigKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @name: BaiduLinkPostUtil
 * @Author: wangshimin
 * @Date: 2020/2/7  14:53
 * @Description:
 */
@Slf4j
@Component
public class BaiduLinkPostUtil {

    @Autowired
    CloseConfig closeConfig;
    @Autowired
    BaseConfig baseConfig;

    @Async("asyncLinkPostExecutor")
    public void Post(String[] Parameters) {
        if (!closeConfig.getMap(CloseKey.BAIDULINK.getValue())) {
            return;
        }
        if (null == Parameters || Parameters.length == 0) {
            log.info("[链接推广] 百度推广失败");
            return;
        }
        Object map = baseConfig.getMap(ConfigKey.BAIDULINK.getValue());
        if (null == map) {
            log.error("未配置百度推广地址信息，无法推送连接");
            return;
        }
        String baiduLink = map.toString();
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            //建立URL之间的连接
            URLConnection conn = new URL(baiduLink).openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("Host", "data.zz.baidu.com");
            conn.setRequestProperty("User-Agent", "curl/7.12.1");
            conn.setRequestProperty("Content-Length", "83");
            conn.setRequestProperty("Content-Type", "text/plain");
            //发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //获取conn对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数
            String param = "";
            for (String s : Parameters) {
                param += s + "\n";
            }
            out.print(param.trim());
            //进行输出流的缓冲
            out.flush();
            //通过BufferedReader输入流来读取Url的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("[链接推广] 百度推广 发送post请求出现异常！");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }

            } catch (IOException ex) {
                log.info("[链接推广] 百度推广 关闭流失败！");
            }
        }
        log.info("[链接推广] 百度推广{} 推送成功 返回值{}", JSONUtils.beanToJson(Parameters), result);
    }
}
